#include "AppTask.h"
#include "FreeRTOS.h"
#include "task.h"
#include "appCar.h"
#include "Delay.h"
#include "appCommunicate.h"

uint8_t recvBuf[32] = {0};
uint8_t sendBuf[32] = {0};

#define START_TASK_PRIORITY        1
#define CONTROL_TASK_PRIORITY      1
#define COMMUNICATE_TASK_PRIORITY  1
#define START_STACK_DEPTH          128
#define CONTROL_STACK_DEPTH        128
#define COMMUNICATE_STACK_DEPTH    128

TaskHandle_t start_task_handle;
TaskHandle_t control_task_handle;
TaskHandle_t communicate_task_handle;

/**
 * @brief 用于与遥控通信的进程
*/
static void AppTaskCommunicate(void *para)
{
	while(1) {
		RecvMsgFromRemote(recvBuf);
		sendBuf[0] = 1;
		sendBuf[1] = 2;
		sendBuf[2] = 3;
	 	SendMsgToRemote(sendBuf);
		vTaskDelay(500);
	}
}

static void AppTaskControl(void *para)
{
	while(1) {
		// ControlCar();
		vTaskDelay(500);
	}
}

/**
 * @brief 创建所有业务进程
*/
static void StartTask(void *para)
{
	BaseType_t xReturn = pdPASS;
	/* 创建通信进程, 用于接收与反馈遥控的信号 */
	xReturn = xTaskCreate((TaskFunction_t) AppTaskCommunicate,
		(char *) "AppTaskCommunicate",
		(configSTACK_DEPTH_TYPE) COMMUNICATE_STACK_DEPTH,
		(void *) NULL,
		(UBaseType_t) COMMUNICATE_TASK_PRIORITY,
		(TaskHandle_t *) communicate_task_handle);
	if (xReturn != pdPASS) {
		goto create_fail;
	}
	/* 创建控制进程, 用于保持平衡 */
	xTaskCreate((TaskFunction_t) AppTaskControl,
		(char *) "AppTaskControl",
		(configSTACK_DEPTH_TYPE) CONTROL_STACK_DEPTH,
		(void *) NULL,
		(UBaseType_t) CONTROL_TASK_PRIORITY,
		(TaskHandle_t *) control_task_handle);
	if (xReturn != pdPASS) {
		goto create_fail;
	}

	vTaskDelete(start_task_handle); 
	return;

create_fail:
	OLED_ShowString(1, 1, "1111 fail");
	return;
}

/**
 * @brief FreeRtos启动，祖先进程创建，由该进程创建后续其他的业务进程, 当所有业务进程创建成功之后杀死该进程
*/
void FreeRtosStart(void)
{
	BaseType_t xReturn = pdPASS;
	xReturn = xTaskCreate((TaskFunction_t) StartTask,
		(char *) "StartTask",
		(configSTACK_DEPTH_TYPE) START_STACK_DEPTH,
		(void *) NULL,
		(UBaseType_t) START_TASK_PRIORITY,
		(TaskHandle_t *) start_task_handle);
	if (xReturn != pdPASS) {
		OLED_ShowString(1, 0, "StartTask fail");
		return;
	}
	vTaskStartScheduler();
}

extern void xPortSysTickHandler(void);
/**
 * @brief 时钟心跳, 实现中断后FreeRtos就有了心跳了
*/
void SysTick_Handler(void)
{
	if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
		xPortSysTickHandler();
	}
}
